const app = getApp()

Page({
  data: {
    favoriteList: []
  },

  onShow() {
    this.loadFavoriteList()
  },

  // 加载收藏列表
  async loadFavoriteList() {
    if (!app.globalData.openid) {
      return
    }

    try {
      const db = wx.cloud.database()
      const { data } = await db.collection('favorites')
        .where({
          userId: app.globalData.openid
        })
        .orderBy('createTime', 'desc')
        .get()
      
      this.setData({ favoriteList: data })
    } catch (error) {
      console.error('加载收藏列表失败：', error)
    }
  },

  // 取消收藏
  async cancelFavorite(e) {
    const { id } = e.currentTarget.dataset
    
    try {
      const db = wx.cloud.database()
      await db.collection('favorites').doc(id).remove()
      
      wx.showToast({
        title: '已取消收藏'
      })
      
      this.loadFavoriteList()
    } catch (error) {
      console.error('取消收藏失败：', error)
    }
  },

  // 跳转到商品详情
  goToDetail(e) {
    const { id } = e.currentTarget.dataset
    wx.navigateTo({
      url: `/pages/products/detail?id=${id}`
    })
  }
}) 